import { _decorator, CCBoolean, Component, Node, Sprite, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FrameAnim')
export class FrameAnim extends Component {

    spriteFrames: SpriteFrame[]
    // 帧的时间间隔
    duration: number = 0.1

    @property(CCBoolean)
    loop: boolean = false;

    @property(CCBoolean)
    playOnLoad: boolean = false;

    private sprite: Sprite

    private isPlaying: boolean = false;

    private playTime: number

    private isLoop: boolean

    private endFunc: Function

    protected onLoad(): void {
        let spriteComp = this.node.getComponent(Sprite)
        if (!spriteComp) {
            spriteComp = this.node.addComponent(Sprite)
        }
        this.sprite = spriteComp;

        this.isPlaying = false;
        this.playTime = 0
        this.isLoop = false;
        this.endFunc = null;

        if (this.playOnLoad) {
            this.sprite.spriteFrame = this.spriteFrames[0]
            if (this.loop) {
                this.playLoop()
            } else {
                this.playOnce(null)
            }
        }
    }

    playOnce(endFunc: Function) {
        this.playTime = 0;
        this.isPlaying = true;
        this.isLoop = false;
        this.endFunc = endFunc;
    }

    playLoop() {
        this.playTime = 0;
        this.isPlaying = true;
        this.isLoop = true;
    }

    stopAnim() {
        this.playTime = 0;
        this.isPlaying = false;
        this.isLoop = false;
    }

    update(deltaTime: number) {
        if (!this.isPlaying) {
            return;
        }
        this.playTime += deltaTime; // 累积我们播放的时间;

        // 计算时间，应当播放第几帧，而不是随便的下一帧，
        // 否则的话，同样的动画1, 60帧，你在30FPS的机器上你会播放2秒，
        // 你在60FPS的机器上你会播放1秒，动画就不同步;

        var index = Math.floor(this.playTime / this.duration); // 向下取整数
        if (this.spriteFrames && this.spriteFrames.length > 0) {
            // index
            if (this.isLoop === false) { // 播放一次
                if (index >= this.spriteFrames.length) { // 非循环播放结束
                    // 精灵显示的是最后一帧;
                    this.sprite.spriteFrame = this.spriteFrames[this.spriteFrames.length - 1];
                    // end 
                    this.isPlaying = false;
                    this.playTime = 0;
                    if (this.endFunc) { // 调用回掉函数
                        this.endFunc();
                    }
                    return;
                }
                else {
                    this.sprite.spriteFrame = this.spriteFrames[index];
                }
            }
            else { // 循环播放;
                while (index >= this.spriteFrames.length) {
                    index -= this.spriteFrames.length;
                    this.playTime -= (this.duration * this.spriteFrames.length);
                }

                //  在合法的范围之内
                this.sprite.spriteFrame = this.spriteFrames[index];
                // end 
            }
        }
    }
}

